<template>
  <button
    :class="['my-checkbox-button', { 'my-checkbox-button-checked': isChecked }]"
    @mousedown="handleMouseDown"
    @mouseup="handleMouseUp"
    @mouseleave="handleMouseLeave"
    :disabled="disabled"
    :data-value="value"
  >
    <slot></slot>
  </button>
</template>

<script>
export default {
  name: 'MyCheckboxButton',
  inject: {
    checkboxGroup: {
      default: null
    }
  },
  props: {
    value: {
      type: [String, Number, Boolean],
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    isChecked() {
      // 使用传统的方式避免 ?. 操作符
      if (this.checkboxGroup) {
        return this.checkboxGroup.value.includes(this.value);
      }
      return false;
    }
  },
  data() {
    return {
      isDragging: false,
      mouseIsDown: false,
    };
  },
  methods: {
    handleMouseDown(event) {
      if (event.button !== 0 || this.disabled) return;
      this.mouseIsDown = true;
      this.isDragging = false;
      document.addEventListener('mousemove', this.handleMouseMove);
    },
    handleMouseUp(event) {
      document.removeEventListener('mousemove', this.handleMouseMove);
      if (!this.isDragging) {
        this.handleClick();
      } else {
        if (this.checkboxGroup) {
          this.checkboxGroup.endDrag(event);
        }
      }
      this.mouseIsDown = false;
    },
    handleMouseLeave() {
      if (this.mouseIsDown) {
        this.isDragging = true;
        if (this.checkboxGroup) {
          this.checkboxGroup.startDrag(this.value);
        }
      }
    },
    handleMouseMove(event) {
      if (this.mouseIsDown && !this.isDragging) {
        this.isDragging = true;
      }
    },
    handleClick() {
      if (this.disabled) return;
      const newChecked = !this.isChecked;
      if (this.checkboxGroup) {
        this.checkboxGroup.toggleCheckbox(this.value, newChecked);
      }
    }
  }
};
</script>

<style scoped>
.my-checkbox-button {
  padding: 8px 16px;
  border: 1px solid #1890ff;
  background-color: white;
  color: #1890ff;
  border-radius: 2px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s;
  outline: none;
  margin: 4px;
  user-select: none;
}

.my-checkbox-button-checked {
  background-color: #1890ff;
  color: white;
}

.my-checkbox-button[disabled] {
  cursor: not-allowed;
  opacity: 0.6;
}
</style>
